﻿using System;
using System.Text;
using OA.Core.Helper;
using Aliyun.OSS;
using System.Security.Cryptography;
using Newtonsoft.Json;

namespace OA.Core.Oss
{
    public static class OssHelper
    {

        /// <summary>
        /// 获取受保护的OSS内容临时链接，有效时间30分钟
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetFileProtectUrl(OssConfig config,string key)
        {
            var client = new OssClient(config.Endpoint, config.AccessKeyId, config.AccessKeySecret);
            var myUrl = client.GeneratePresignedUri(config.BucketName, key, DateTime.Now.AddMinutes(30));
            return myUrl.AbsoluteUri.Replace("http://", "https://");
        }

        public static string GetUrl(OssConfig config, string key)
        {
            var client = new OssClient(config.Endpoint, config.AccessKeyId, config.AccessKeySecret);
            var myUrl = client.GeneratePresignedUri(config.BucketName, key);
            return myUrl.AbsoluteUri.Replace("http://", "https://");
        }

        /// <summary>
        /// 获取普通上传的签名
        /// </summary>
        /// <returns></returns>
        public static PolicyInfo GetPolicyInfo(OssConfig config, string userID)
        {
            string key = "upload" + "/" + userID + "/Files/" + DateTime.Now.ToString("yyyy/") + DateTime.Now.ToString("MM/") + DateTime.Now.ToString("ddHHmm") + "_";
            OssClient client = new OssClient(config.Endpoint, config.AccessKeyId, config.AccessKeySecret);
            DateTime now = DateTime.Now;
            DateTime ex = now.AddMinutes(5);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.AddConditionItem("content-length-range", 0L, 1048576000L);
            policyConds.AddConditionItem(MatchMode.StartWith, "key", key);
            string postPolicy = client.GeneratePostPolicy(ex, policyConds);
            byte[] binaryData = Encoding.Default.GetBytes(postPolicy);
            string encodedPolicy = Convert.ToBase64String(binaryData);
            var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(config.AccessKeySecret));
            var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(encodedPolicy));
            var signature = Convert.ToBase64String(hashBytes);
            string host = string.Empty;
            host = "https://" + config.BucketName + "." + config.Endpoint;
            var callbackJson = new
            {
                callbackUrl = config.OssCallBackUrl,
                callbackBody = "bucket=${bucket}&url=${object}&size=${size}&mimeType=${mimeType}&my_var=" + config.Endpoint,
                callbackBodyType = "application/x-www-form-urlencoded"//这里的类型就是上面文本的类型
            };
            byte[] bytes = Encoding.Default.GetBytes(JsonConvert.SerializeObject(callbackJson));
            string callbackBody = Convert.ToBase64String(bytes);


            return new PolicyInfo()
            {
                Accessid = config.AccessKeyId,
                Signature = signature,
                Expire = CommonHelper.GetTimeStamp(50000),
                Dir = key,
                Host = host,
                Policy = encodedPolicy,
                CallbackBody = callbackBody
            };

        }


        public static PolicyInfo GetRichTextPolicyInfo(OssConfig config, string userID)
        {
           
            string key = "richtext" + "/" + userID + "/" + DateTime.Now.ToString("yyyy/") + DateTime.Now.ToString("MM/") + DateTime.Now.ToString("ddHHmm") + "_";
            OssClient client = new OssClient(config.Endpoint, config.AccessKeyId, config.AccessKeySecret);
            DateTime now = DateTime.Now;
            DateTime ex = now.AddMinutes(5);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.AddConditionItem("content-length-range", 0L, 1048576000L);
            policyConds.AddConditionItem(MatchMode.StartWith, "key", key);

            string postPolicy = client.GeneratePostPolicy(ex, policyConds);
            byte[] binaryData = Encoding.Default.GetBytes(postPolicy);
            string encodedPolicy = Convert.ToBase64String(binaryData);
            var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(config.AccessKeySecret));
            var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(encodedPolicy));
            var signature = Convert.ToBase64String(hashBytes);
            string host = "https://" + config.BucketName + "." + config.Endpoint;

            var callbackJson = new
            {
                callbackUrl = config.OssCallBackUrl,
                callbackBody = "bucket=${bucket}&url=${object}&size=${size}&mimeType=${mimeType}&my_var=" + config.Endpoint,
                callbackBodyType = "application/x-www-form-urlencoded"//这里的类型就是上面文本的类型
            };

            byte[] bytes = Encoding.Default.GetBytes(JsonConvert.SerializeObject(callbackJson));
            string callbackBody = Convert.ToBase64String(bytes);
            return new PolicyInfo()
            {
                Accessid = config.AccessKeyId,
                Signature = signature,
                Expire = CommonHelper.GetTimeStamp(50000),
                Dir = key,
                Host = host,
                Policy = encodedPolicy,
                CallbackBody = callbackBody
            };
        }
    }
}
